package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.StringUtil;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.MenuMapper;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceimpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize); //分页
        //判断是否在模糊查询
        if(StringUtil.isEmpty(queryString)){
            //正常遍历  查找所有列表
            //一级menu
            LinkedHashSet<Menu> pMenus = menuMapper.findAllPMenus();
            for (Menu pMenu : pMenus) {
                List<Menu> cMenus = menuMapper.findCMenusByPid(pMenu.getId());
                pMenu.setChildren(cMenus);
            }
            List list = new LinkedList();
            list.addAll(pMenus);
            return new PageResult(Long.valueOf(pMenus.size()),list);
        }
        //模糊查询
        Page<Menu> menuList = menuMapper.findByCondition(queryString);
        long total = menuList.getTotal();   //数据量
        List<Menu> rows = menuList.getResult();
        return new PageResult(total,rows);
    }

    @Override
    public void add(Menu menu) {
        menuMapper.add(menu);
    }

    @Override
    public void delete(Integer id) {
        //删除外键关联
        menuMapper.deleteAssociation(id);
        //删除基本数据
        menuMapper.delete(id);
    }

    @Override
    public void update(Menu menu) {
        menuMapper.update(menu);
    }

    //遍历菜单信息
    @Override
    public List<Menu> findAll() {
        return menuMapper.findAll();
    }

    @Override
    public List<Menu> findByMenuIds(Integer id) {
        return menuMapper.findByMenuIds(id);
    }
}
